package com.weigecoder.auth.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.weigecoder.auth.service.*;
import com.weigecoder.common.result.Result;
import com.weigecoder.common.utils.MD5;
import com.weigecoder.model.system.SysUser;
import com.weigecoder.vo.system.SysUserQueryVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

/**
 * 用户表 前端控制器
 */
@Api(tags = "用户管理接口")
@RestController
@RequestMapping("/admin/system/sysUser")
public class SysUserController {

    @Autowired
    private SysUserService service;

    /*@Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysDeptService sysDeptService;
    @Autowired
    private SysPostService sysPostService;*/

    @ApiOperation(value = "更新状态")
    @PreAuthorize("hasAuthority('bnt.sysUser.updatestatus')")
    @GetMapping("updateStatus/{id}/{status}")
    public Result updateStatus(@PathVariable Long id, @PathVariable Integer status) {
        service.updateStatus(id, status);
        return Result.ok();
    }

    //用户条件分页查询
    /*@ApiOperation("用户条件分页查询")
    @PreAuthorize("hasAuthority('bnt.sysUser.list')")
    @GetMapping("{page}/{limit}")
    public Result index(@PathVariable Long page,
                        @PathVariable Long limit,
                        SysUserQueryVo sysUserQueryVo) {
        //创建page对象
        Page<SysUser> pageParam = new Page<>(page, limit);

        //封装条件，判断条件值不为空
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        //获取条件值
        String keyword = sysUserQueryVo.getKeyword();
        String createTimeBegin = sysUserQueryVo.getCreateTimeBegin();
        String createTimeEnd = sysUserQueryVo.getCreateTimeEnd();
        //判断条件值不为空
        //like 模糊查询
        if (!StringUtils.isEmpty(keyword)) {
            wrapper.like(SysUser::getUsername, keyword)
                    .or()
                    .like(SysUser::getPhone, keyword)
                    .or()
                    .like(SysUser::getName, keyword);
        }
        //ge 大于等于
        if (!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge(SysUser::getCreateTime, createTimeBegin);
        }
        //le 小于等于
        if (!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.le(SysUser::getCreateTime, createTimeEnd);
        }

        //调用mp的方法实现条件分页查询
        IPage<SysUser> pageModel = service.page(pageParam, wrapper);

        List<SysUser> sysUserList = pageModel.getRecords();
        for (SysUser sysUser : sysUserList) {
            LambdaQueryWrapper<SysUserRole> sysUserRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();
            sysUserRoleLambdaQueryWrapper.eq(SysUserRole::getUserId, sysUser.getId());
            List<SysUserRole> sysUserRoles = sysUserRoleService.list(sysUserRoleLambdaQueryWrapper);
            List<Long> collect = sysUserRoles.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
            List<SysRole> roleList = new ArrayList<>();
            if (!Objects.isNull(collect)) {
                for (Long roleId : collect) {
                    SysRole sysRole = sysRoleService.getById(roleId);
                    roleList.add(sysRole);
                }
                sysUser.setRoleList(roleList);
            } else {
                sysUser.setRoleList(null);
            }
            Long deptId = sysUser.getDeptId();
            Long postId = sysUser.getPostId();
            if (!Objects.isNull(deptId)) {
                SysDept sysDept = sysDeptService.getById(deptId);
                sysUser.setDeptName(sysDept.getName());
            } else {
                sysUser.setDeptName("暂无");
            }
            if (!Objects.isNull(postId)) {
                SysPost sysPost = sysPostService.getById(postId);
                sysUser.setPostName(sysPost.getName());
            } else {
                sysUser.setPostName("暂无");
            }
        }

        return Result.ok(pageModel);
    }*/

    @ApiOperation("用户条件分页查询")
    @PreAuthorize("hasAuthority('bnt.sysUser.list')")
    @GetMapping("{page}/{limit}")
    public Result index(@PathVariable Long page,
                        @PathVariable Long limit,
                        SysUserQueryVo sysUserQueryVo) {
        Page<SysUser> pageParam = new Page<>(page, limit);
        IPage<SysUser> pageModel = service.findSysUserPage(pageParam, sysUserQueryVo);
        return Result.ok(pageModel);
    }

    @ApiOperation(value = "获取用户")
    @PreAuthorize("hasAuthority('bnt.sysUser.list')")
    @GetMapping("get/{id}")
    public Result get(@PathVariable Long id) {
        SysUser user = service.getById(id);
        return Result.ok(user);
    }

    @ApiOperation(value = "保存用户")
    @PreAuthorize("hasAuthority('bnt.sysUser.add')")
    @PostMapping("save")
    public Result save(@RequestBody SysUser user) {
        //密码进行加密，使用MD5
        String passwordMD5 = MD5.encrypt(user.getPassword());
        user.setPassword(passwordMD5);

        service.save(user);
        return Result.ok();
    }

    @ApiOperation(value = "更新用户")
    @PreAuthorize("hasAuthority('bnt.sysUser.update')")
    @PutMapping("update")
    public Result updateById(@RequestBody SysUser user) {
        service.updateById(user);
        return Result.ok();
    }

    @ApiOperation(value = "删除用户")
    @PreAuthorize("hasAuthority('bnt.sysUser.remove')")
    @DeleteMapping("remove/{id}")
    public Result remove(@PathVariable Long id) {
        service.removeById(id);
        return Result.ok();
    }

}

